
// request
;(function (win, $) {
    app.namespace('app.admin')

    $.extend(app.admin, {
        data: {
            user: {}
        },
        init: function () {
            this.info()
        },
        info: function () {
            var user = JSON.parse(app.atob(localStorage.getItem('milu.article.user')))

            if (user) {
                this.data.user = user
            }
        },
        getUserInfo: function () {
            return JSON.parse(app.atob(localStorage.getItem('milu.article.user')))
        },
        /**
         * 构造树型结构数据
         * @param {*} data 数据源
         * @param {*} id id字段 默认 'id'
         * @param {*} parentId 父节点字段 默认 'parentId'
         * @param {*} children 孩子节点字段 默认 'children'
         */
        handleTree: function (data, id, parentId, children) {
            // debugger
            let config = {
                id: id || 'id',
                parentId: parentId || 'parentId',
                childrenList: children || 'children'
            }

            var childrenListMap = {}
            var nodeIds = {}
            var tree = []

            if (!data) {
                return
            }

            for (let d of data) {
                let parentId = d[config.parentId]
                if (!childrenListMap[parentId]) {
                    childrenListMap[parentId] = []
                }
                nodeIds[d[config.id]] = d
                childrenListMap[parentId].push(d)
            }

            for (let d of data) {
                let parentId = d[config.parentId]
                if (!nodeIds[parentId]) {
                    d.label = d?.title || ''
                    tree.push(d)
                }
            }

            for (let t of tree) {
                adaptToChildrenList(t)
            }

            function adaptToChildrenList(o) {
                if (childrenListMap[o[config.id]]) {
                    o[config.childrenList] = childrenListMap[o[config.id]]
                }
                if (o[config.childrenList]) {
                    for (let c of o[config.childrenList]) {
                        c.label = c?.title || ''
                        adaptToChildrenList(c)
                    }
                }
            }

            return tree
        }
    })

}(window, jQuery))

